package com.xxx.common.mysql.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.xxx.common.base.bo.UserTokenBO;
import com.xxx.common.base.util.TokenUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Optional;


@Component
public class MybatisPlusHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Date time = new Date();
        UserTokenBO userTokenBO = TokenUtil.getUserTokenBO();
        String user = Optional.ofNullable(userTokenBO).map(UserTokenBO::getUserId).map(String::valueOf).orElse("1");
        this.strictInsertFill(metaObject, "createTime", Date.class, time);
        this.strictInsertFill(metaObject, "createBy", String.class, user);
        this.strictUpdateFill(metaObject, "updateTime", Date.class, time);
        this.strictInsertFill(metaObject, "updateBy", String.class, user);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Date time = new Date();
        UserTokenBO userTokenBO = TokenUtil.getUserTokenBO();
        String user = Optional.ofNullable(userTokenBO).map(UserTokenBO::getUserId).map(String::valueOf).orElse("1");
        this.strictUpdateFill(metaObject, "updateTime", Date.class, time);
        this.strictInsertFill(metaObject, "updateBy", String.class, user);
    }
}